package com.campus.client.view;

import com.campus.client.controller.StudentCourseController;
import com.campus.client.net.ClientConnector;
import com.campus.common.vo.Classroom;
import com.campus.common.vo.Course;
import com.campus.common.vo.User;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.layout.*;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class StudentCourseView {

    private Accordion accordion;
    private ScrollPane scrollPane;
    private String queryKeyword;
    private User user;

    /** 课程视图模式 */
    public enum CourseViewMode {
        SELECTABLE, SELECTED, QUERY, ALL, FIRST_TIME, RETAKE
    }

    private CourseViewMode mode;

    public StudentCourseView(CourseViewMode mode, User user) {
        this.mode = mode;
        this.user = user;
        accordion = new Accordion();
        initScrollPane();
        loadCourses();
    }

    public StudentCourseView(CourseViewMode mode, String keyword, User user) {
        this.mode = mode;
        this.queryKeyword = keyword;
        this.user = user;
        accordion = new Accordion();
        initScrollPane();
        loadCourses();
    }

    public ScrollPane getView() {
        return scrollPane;
    }

    private VBox mainBox;

    /** 初始化 ScrollPane 和表头 */
    private void initScrollPane() {
        mainBox = new VBox(0);
        mainBox.setFillWidth(true);

        accordion = new Accordion();
        accordion.setMaxWidth(Double.MAX_VALUE);

        // 表头 HBox
        HBox header = new HBox();
        header.getStyleClass().add("academic-course-header");
        header.setAlignment(Pos.CENTER_LEFT);
        header.setPadding(new Insets(4, 10, 4, 10));
        header.setSpacing(5);
        header.setMaxWidth(Double.MAX_VALUE);

        // 列：课程编号（固定宽）
        Label lblCourseId = new Label("课程编号");
        lblCourseId.setPrefWidth(140);
        lblCourseId.setAlignment(Pos.CENTER_LEFT);

        // 列：课程名称（自适应宽度）
        Label lblCourseName = new Label("课程名称");
        HBox.setHgrow(lblCourseName, Priority.ALWAYS);
        lblCourseName.setMaxWidth(Double.MAX_VALUE);
        lblCourseName.setAlignment(Pos.CENTER_LEFT);

        // 列：学分（固定宽）
        Label lblCredit = new Label("学分");
        lblCredit.setPrefWidth(80);
        lblCredit.setAlignment(Pos.CENTER);

        // 列：开课学院（固定宽）
        Label lblDepartment = new Label("开课学院");
        lblDepartment.setPrefWidth(120);
        lblDepartment.setAlignment(Pos.CENTER);


        // 列：教学班个数（固定宽）
        Label lblClassCount = new Label("教学班个数");
        lblClassCount.setPrefWidth(100);
        lblClassCount.setAlignment(Pos.CENTER_RIGHT);

        // 列：选课状态（固定宽）
        Label lblStatus = new Label("选课状态");
        lblStatus.setPrefWidth(100);
        lblStatus.setAlignment(Pos.CENTER);

        header.getChildren().addAll(lblCourseId, lblCourseName, lblCredit, lblDepartment, lblClassCount, lblStatus);

        mainBox.getChildren().addAll(header, accordion);

        scrollPane = new ScrollPane(mainBox);
        scrollPane.setFitToWidth(true);
        scrollPane.setFitToHeight(true);
        scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
        scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);

        // 保证表头宽度跟随 ScrollPane
        header.prefWidthProperty().bind(scrollPane.widthProperty().subtract(10));
        header.maxWidthProperty().bind(scrollPane.widthProperty().subtract(10));
    }

    /** 加载课程数据 */
    private void loadCourses() {
        try {
            String studentId = user.getId();
            StudentCourseController controller = new StudentCourseController(new ClientConnector("172.20.10.2", 8888));

            // 当前模式课程列表
            List<Course> courses;
            switch (mode) {
                case SELECTABLE -> courses = controller.viewAvailableCourses(studentId);
                case SELECTED -> courses = controller.viewSelectedCourses(studentId);
                case ALL -> courses = controller.viewAllCourses();
                case QUERY -> courses = controller.queryCourses(queryKeyword);
                case FIRST_TIME -> courses = controller.viewFirstTimeCourses(studentId);
                case RETAKE -> courses = controller.viewRetakeCourses(studentId);
                default -> courses = List.of();
            }

            // 获取已选课程（无论当前模式是什么，都拿来对比状态）
            List<Course> selectedCourses = controller.viewSelectedCourses(studentId);
            Set<String> selectedIds = selectedCourses.stream()
                    .map(Course::getCourseId)
                    .collect(Collectors.toSet());

            accordion.getPanes().clear();

            if (courses == null || courses.isEmpty()) {
                Label emptyLabel = new Label("没有找到课程");
                TitledPane pane = new TitledPane("提示", emptyLabel);
                pane.getStyleClass().add("custom-titled-pane");
                accordion.getPanes().add(pane);
                return;
            }

            for (Course course : courses) {
                TitledPane pane = new TitledPane();
                pane.getStyleClass().add("custom-titled-pane");
                pane.setCollapsible(true);
                pane.setExpanded(false);

                // ===== 课程行 HBox =====
                HBox courseRow = new HBox();
                courseRow.getStyleClass().add("course-row");
                courseRow.setAlignment(Pos.CENTER_LEFT);
                courseRow.setSpacing(5);
                courseRow.setMaxWidth(Double.MAX_VALUE);

                // 列1：课程编号 + 课程详情
                VBox courseIdCol = new VBox(2);
                courseIdCol.setPrefWidth(140);
                Label lblId = new Label("    " + course.getCourseId());
                lblId.setAlignment(Pos.CENTER_RIGHT);
                Label detailLink = new Label("课程详情");
                detailLink.getStyleClass().add("detail-link");
                detailLink.setPadding(new Insets(0, 0, 0, 8));
                detailLink.setOnMouseClicked(e -> pane.setExpanded(!pane.isExpanded()));
                courseIdCol.getChildren().addAll(lblId, detailLink);

                // 列2：课程名称
                Label lblName = new Label("    " + course.getCourseName());
                lblName.setMaxWidth(Double.MAX_VALUE);
                lblName.setAlignment(Pos.CENTER_LEFT);
                HBox.setHgrow(lblName, Priority.ALWAYS);

                // 列3：学分
                Label lblCredit = new Label("        " + String.valueOf(course.getCredit()));
                lblCredit.setPrefWidth(80);
                lblCredit.setAlignment(Pos.CENTER_LEFT);
                // 列：开课学院
                Label lblDepartmentValue = new Label(course.getDepartment());
                lblDepartmentValue.setPrefWidth(120);
                lblDepartmentValue.setAlignment(Pos.CENTER);


                // 列4：教学班个数
                Label lblClassCount = new Label(String.valueOf(course.getClassrooms().size()));
                lblClassCount.setPrefWidth(100);
                lblClassCount.setAlignment(Pos.CENTER);

                // ⭐ 列5：选课状态（根据 selectedIds 判断）
                Label lblStatus = new Label();
                lblStatus.setPrefWidth(100);
                lblStatus.setAlignment(Pos.CENTER);
                if (selectedIds.contains(course.getCourseId())) {
                    lblStatus.setText("已选 ✔");
                    lblStatus.setStyle("-fx-text-fill: green; -fx-font-weight: bold;");
                } else {
                    lblStatus.setText("未选");
                    lblStatus.setStyle("-fx-text-fill: grey; -fx-font-weight: bold;");
                }

                courseRow.getChildren().addAll(courseIdCol, lblName, lblCredit, lblDepartmentValue, lblClassCount, lblStatus);


                // 绑定宽度
                courseRow.prefWidthProperty().bind(scrollPane.widthProperty().subtract(10));
                courseRow.maxWidthProperty().bind(scrollPane.widthProperty().subtract(10));

                pane.setGraphic(courseRow);

                // ===== 班级卡片容器 =====
                FlowPane classContainer = new FlowPane();
                classContainer.setHgap(10);
                classContainer.setVgap(10);
                classContainer.setPadding(new Insets(5, 10, 10, 10));

                for (Classroom c : course.getClassrooms()) {
                    VBox card = new VBox(8);
                    card.getStyleClass().add("card");

                    HBox topRow = new HBox(10);
                    Label lblTeacher = new Label("教师: " + (c.getTeacher() != null ? c.getTeacher().getName() : ""));
                    lblTeacher.getStyleClass().add("teacher-name-label");
                    Region spacer = new Region();
                    HBox.setHgrow(spacer, Priority.ALWAYS);
                    topRow.getChildren().addAll(lblTeacher, spacer);

                    Label lblClassId = new Label("班级编号: " + c.getClassId());
                    Label lblTime = new Label("上课时间: " + c.getCourseTime());
                    Label lblLocation = new Label("上课地点: " + c.getCourseLocation());
                    Label lblCapacity = new Label("人数/容量: " + c.getSelectedCount() + "/" + c.getCapacity());

                    HBox btnBox = new HBox(8);
                    btnBox.getStyleClass().add("bottom-row");

                    if (mode == CourseViewMode.SELECTABLE || mode == CourseViewMode.QUERY) {
                        Button btnSelect = new Button("选课");
                        btnSelect.getStyleClass().add("action-button");
                        btnSelect.setOnAction(e -> {
                            try {
                                String msg = controller.selectCourse(studentId, c.getClassId());
                                showAlert(msg);
                                if (msg.contains("成功")) {
                                    lblStatus.setText("已选 ✔");
                                    lblStatus.setStyle("-fx-text-fill: green; -fx-font-weight: bold;");
                                    // ⭐ 选课成功后替换为退课按钮
                                    btnBox.getChildren().clear();
                                    Button btnDrop = createDropButton(controller, studentId, c.getClassId(), lblStatus, btnBox);
                                    btnBox.getChildren().add(btnDrop);
                                }
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        });
                        btnBox.getChildren().add(btnSelect);
                    } else if (mode == CourseViewMode.SELECTED || mode == CourseViewMode.QUERY) {
                        Button btnDrop = createDropButton(controller, studentId, c.getClassId(), lblStatus, btnBox);
                        btnBox.getChildren().add(btnDrop);
                    }
// ⭐ FIRST_TIME / RETAKE 特殊逻辑
                    else if (mode == CourseViewMode.FIRST_TIME || mode == CourseViewMode.RETAKE) {
                        Button btnSelect = new Button("选课");
                        btnSelect.getStyleClass().add("action-button");
                        btnSelect.setOnAction(e -> {
                            try {
                                String msg = controller.selectCourse(studentId, c.getClassId());
                                showAlert(msg);
                                if (msg.contains("成功")) {
                                    lblStatus.setText("已选 ✔");
                                    lblStatus.setStyle("-fx-text-fill: green; -fx-font-weight: bold;");
                                    // ⭐ 替换成退课按钮
                                    btnBox.getChildren().clear();
                                    Button btnDrop = createDropButton(controller, studentId, c.getClassId(), lblStatus, btnBox);
                                    btnBox.getChildren().add(btnDrop);
                                }
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        });
                        btnBox.getChildren().add(btnSelect);
                    }


                    card.getChildren().addAll(topRow, lblClassId, lblTime, lblLocation, lblCapacity, btnBox);
                    classContainer.getChildren().add(card);
                }

                pane.setContent(classContainer);
                accordion.getPanes().add(pane);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void showAlert(String msg) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION, msg, ButtonType.OK);
        alert.showAndWait();
    }
    private Button createDropButton(StudentCourseController controller, String studentId, String classId, Label lblStatus, HBox btnBox) {
        Button btnDrop = new Button("退课");
        btnDrop.getStyleClass().add("danger-button");
        btnDrop.setOnAction(e -> {
            try {
                String msg = controller.dropCourse(studentId, classId);
                showAlert(msg);
                if (msg.contains("成功")) {
                    lblStatus.setText("未选");
                    lblStatus.setStyle("-fx-text-fill: grey; -fx-font-weight: bold;");
                    // ⭐ 替换回选课按钮
                    btnBox.getChildren().clear();
                    Button btnSelect = new Button("选课");
                    btnSelect.getStyleClass().add("action-button");
                    btnSelect.setOnAction(ev -> {
                        try {
                            String m = controller.selectCourse(studentId, classId);
                            showAlert(m);
                            if (m.contains("成功")) {
                                lblStatus.setText("已选 ✔");
                                lblStatus.setStyle("-fx-text-fill: green; -fx-font-weight: bold;");
                                btnBox.getChildren().clear();
                                btnBox.getChildren().add(createDropButton(controller, studentId, classId, lblStatus, btnBox));
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    });
                    btnBox.getChildren().add(btnSelect);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        });
        return btnDrop;
    }

}
